<?php
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;

use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;


/**
 * 会员接口
 */
class  WechatminiController extends Controller
{

    protected $config;
    protected $app;

    public function __construct()
    {
        $this->config = [
            'app_id' => 'wxe53ec042d5c44631',
            'secret' => '2ea024fba0be2d05739b7c2c43d05a5e',


            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

//            'log' => [
//                'level' => 'debug',
//                'file' => __DIR__ . '/wechat.log',
//            ],
        ];
        $this->app = Factory::miniProgram($this->config);

    }

    //根据code获取 sessionkey和openid
    public function getOpenidFromCode(Request $request){

        $code = $request->code;
        $result = $this->app->auth->session($code);
        if(isset($result['openid'])&&$result['openid']){
           return $this->success($result);
        }else{
           return  $this->error('获取失败');
        }
    }


    //消息解密
    public function encryptor($session,$iv,$encryptedData){

        $decryptedData = $this->app->encryptor->decryptData($session, $iv, $encryptedData);
        return $decryptedData;
    }

    //发送订阅消息
    public function send_msg($order_id,$tmp_id='GEr0hcIF0fbSLXFpdHWPtcQnelD6EMsBEx9YLAO4bOM'){
        $order = Db::table('order')->find($order_id);
        $user = Db::table('user')->find($order['user_id']);

        if(!$user['openid']){
            return;
        }

        $data = [
            'template_id' => $tmp_id, // 所需下发的订阅模板id
            'touser' => $user['openid'],     // 接收者（用户）的 openid
            'page' => 'pages/orderRunning/orderRunning?orderid='.$order_id,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            //订单号
            //{{character_string1.DATA}}
            //
            //类型
            //{{thing12.DATA}}
            //
            //订单金额
            //{{amount10.DATA}}
            //
            //完成时间
            //{{time4.DATA}}
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'character_string1' => [
                    'value' => $order['order_num'],
                ],
                'thing12' => [
                    'value' => $order['command_name'],
                ],
                'amount10' => [
                    'value' => $order['money'],
                ],
                'time4' => [
                    'value' => date("Y-m-d H:i:s",time()),
                ],
            ],
            //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
           'miniprogram_state' => 'trial'
        ];

        $this->app->subscribe_message->send($data);
    }


}
